<?php

namespace Apps\AppApi\Method\BeautyParlor;

use AMap\LBSCloud;
use Apps\Common\Libs\PicUrl;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\BeautyParlorTag; 
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Models\BeautyParlorAttr;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\SysOpenCity;
use Apps\Common\Models\OmBanner;
use Apps\Common\Models\BeautyParlor;
/**
 * 附近美容院
 * @package Apps\AppApi\Method\BeautyParlor
 */
class Lbs extends BaseMethod
{
    /**
     * @var \Apps\Common\Models\BeautyParlor array
     */
    private $parlors = [];
    public function run()
    {
        //先验证城市是否开通 modify by tanjinyun 2016/01/11
        $city_code = $this->getDataItem('city_code');
        
        if ($city_code==null ||$city_code==''){
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR,"城市编码为空");exit;
        }
        $is_open = SysOpenCity::findFirst(
            [
                'columns'=>"city_id",
                'conditions' => "city_code = $city_code AND city_state = 1",
            ]);
        
        if (!$is_open->city_id>0){
            return $this->errorLog(ResultStatus::CITY_NOT_OPEN,"城市未开通");exit;
        }
        $longitude = $this->getDataItem('longitude',0);
        $latitude = $this->getDataItem('latitude',0);
        $page = intval($this->getDataItem('page',1));
        $medal = intval($this->getDataItem('medal',0));
        $keyword = trim($this->getDataItem('keyword',null));
        $limit = $this->getConfig()->limit;
//                $longitude = 106.515605;
//                $latitude = 29.539727;
        $config = $this->getDi()->get('appConfig')->amap->lbs_cloud;
        $key = $config->key;
        $signKey = $config->sign_key;
        $tableId = $config->table_id;
        $syncLogTableName = 'beauty_parlor_amap_sync_log';

        //v2.0新增 筛选 
        $filter = $medal==1?"medal_verify:1":null;

        $arr = explode(' ', $keyword);
        $keyword = implode('|', $arr);
        $keywords = $keyword!=null?$keyword:null;
        
        $lbs = new LBSCloud($key, $signKey, $tableId, $syncLogTableName);
        
        $result = $lbs->around($latitude, $longitude, $limit, $page,$filter,$keywords);
        
        
        if($result->status) {
//         	var_dump($result);exit;
            foreach($result->response as $data) {
                
                /**
                 * modify by jinyu
                 * 查询美容院扩展信息
                 */ 
                $info = BeautyParlor::query()
                ->columns([
                    'bp_id',
                    'bp_name',
                    'bp_address',
                    'bp_cover',
                    'bp_tel',
                    'bp_medal',
                    'b.open_time',
                    'b.close_time',
                    'b.low_price',
                    'b.open_year',
                    'b.shop_area',
                    'b.service_num',
                    'b.facilities'
                ])
                ->leftJoin('Apps\Common\Models\BeautyParlorAttr','Apps\Common\Models\BeautyParlor.bp_id = b.beauty_parlor_id','b')
                ->where('Apps\Common\Models\BeautyParlor.bp_id=:bp_id: AND Apps\Common\Models\BeautyParlor.bp_state >0')
                ->bind(['bp_id' => $data['bp_id']])
                ->execute()->getFirst();
                
                if ($info){
                    $this->parlors[] = [
                        'id' => $info['bp_id'],
                        'name' => $info['bp_name'],
                        'cover' => PicUrl::BeautyParlorCover($info['bp_cover'], $this->getDi()),
                        'address' => $info['bp_address'],
                        'tel' => $info['bp_tel'],
                        'tags' => $this->formatTagsV2($info['bp_id']),
                        'distance' => $this->formatDistance($data['_distance']),
                        'medal_verify' => \Apps\Common\Libs\BeautyParlor::getMedalVerify($info['bp_medal']),
                        'open_time' => $info['open_time']==null?'':$info['open_time'],
                        'close_time' => $info['close_time']==null?'':$info['close_time'],
                        'low_price' => $info['low_price']==null?'':$info['low_price'],
                        'open_year' => $info['open_year']==null?'':$info['open_year'],
                        'shop_area' => $info['shop_area']==null?'':$info['shop_area'],
                        'service_num' => $info['service_num']==null?'':$info['service_num'],
                        'facilities' => $info['facilities']==null?null:(json_decode($info['facilities'])?:null),
                    ];
                }
                else{
                    continue;
                }
                
            }
        }
        
        /**
         * 第一页获取banner
         */
        if ($page==1){
        
            $banner = OmBanner::query()
            ->columns(['banner_data'])
            ->where('state = 1 AND banner_name =3 AND city_id in(0, :city_id:)')
            ->bind(['city_id'=>$is_open->city_id])
            ->execute()->toArray();

            foreach ($banner as $k => $v){

                $data = json_decode($v['banner_data']);

                $temp[$k]['url'] =  PicUrl::DefaultPics($data->url,$this->getDi());
                $temp[$k]['link_type'] = $data->link_type;
                $temp[$k]['link_data'] = !empty(json_decode($data->link_data))?json_decode($data->link_data):null;
            }
        }
        
        
        $list['banner'] = $temp;
        $list['parlors'] = empty($this->parlors)?null:$this->parlors;
        
        $this->setResult($list);
    }
    
    /**
     * v2版本 不验证 是否存在标签数据 都当标签已存在
     * @date: 2016年1月11日 
     * @author: 545
     */
    private function formatTagsV2($bp_id){
        $tag = $this->getBeautyParlorTags($bp_id);
        return $tag;
    }
    /**
     * 格式化标签
     * @date: 2016年1月11日 
     * @author: 545
     */
    private function formatTags($tags,$bp_id)
    {
        $ds = [];
        if($tags) {
            $ds = explode(',', $tags);
            foreach ($ds as $r){
            	$wherearr[]="Apps\Common\Models\BeautyParlorTagInfo.tag_title = '$r' and b.bp_id = $bp_id";
            }
            $where = implode(" or ",$wherearr);
            $list=BeautyParlorTagInfo::query()
            ->columns(['Apps\Common\Models\BeautyParlorTagInfo.tag_title','b.sort'])
            ->leftJoin('Apps\Common\Models\BeautyParlorTag','Apps\Common\Models\BeautyParlorTagInfo.tag_id=b.tag_id','b')
            ->where($where)
            ->orderBy('b.sort asc')
            ->execute()->toArray();  
        }
        unset($ds);
        foreach ($list as $r){
        	$ds[]=$r['tag_title'];
        }
        return $ds;
    }

    private function formatDistance($distance)
    {
        $show = $distance;
        if($distance > 1000) {
            $show = number_format($distance / 1000, 1) . 'K';
        }
        return $show . 'M';
    }
}
/*
 * id	店铺ID
name	店铺名称
cover	封面
address	地址
tags	店铺标签数组，最多设置3个
distance	距离
medal_refund	退款保障，1-拥有此属性，0-没有此属性
medal_verify	深度验店，1-拥有此属性，0-没有此属性
 */